package com.pro.xwt.rest.aspect;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pro.xwt.common.model.BMessage;
import com.pro.xwt.common.model.BTask;
import com.pro.xwt.common.service.BMessageService;
import com.pro.xwt.common.service.BTaskService;
import com.pro.xwt.common.utils.Common;


@Component
@Aspect
public class MessageAspect {
	@Autowired
	private BMessageService bMessageService;
	@Autowired
	private BTaskService bTaskService;
	/**
	 * 修改业务逻辑方法切入点 定义在controller包里的以update为前缀的方法的执行
	 */
	@Pointcut("execution(* com.pro.xwt.common.service.BTaskService.updateComState(..))")
	public void updateServiceCall() {
		
		}
	
	 
	
	/**
	 * 添加业务逻辑方法切入点 定义在controller包里的以add为前缀的方法的执行
	 */
    @Pointcut("execution(* com.pro.xwt.common.service.BTaskService.insert(..))")
	public void insertServiceCall(){
	}
    /*
     * 查询消息切面
     */
    @Pointcut("execution(* com.pro.xwt.common.service.BMessageService.selectAll(..))")
	public void selectServiceCall(){
	}
    
    @AfterReturning(value = "selectServiceCall()", argNames = "rtv", returning = "rtv")
    public void selectServiceCallCalls(JoinPoint joinPoint, Object rtv){
    	
    	if (joinPoint.getArgs() == null) {// 没有参数
			return;
		}
    	String execEmpId= (String) ((Map<?, ?>)joinPoint.getArgs()[0]).get("accpEmpId");
    	List<BTask>  bTasks = bTaskService.selectTasks(execEmpId);
    	bMessageService.insertMessage(bTasks);
    	
    	
    }
	/**
	 * 添加任务日志(后置通知)
	 * 
	 * @param joinPoint
	 * @param rtv
	 * @throws Throwable
	 */
	@AfterReturning(value = "insertServiceCall()", argNames = "rtv", returning = "rtv")
	public void insertServiceCallCalls(JoinPoint joinPoint, Object rtv)
			throws Throwable {
		Date date = new Date();
		//过期时间
		//Date expireTime = new Date(date.getTime()+24*60*60*1000);
		BMessage bm = new BMessage();
		BMessage bm1 = new BMessage();
		
		// 判断参数
		if (joinPoint.getArgs() == null) {// 没有参数
			return;
		}
		//消息过期时间
		Date expireTime = new Date(date.getTime()+24*60*60*1000);
		// 获取方法名
		String methodName = joinPoint.getSignature().getName();
		// 消息绑定任务id
		String taskId = (String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getId");
		//接收人
		String accpEmpId=(String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getExecEmpId");
		//接收人name
		//String accEmpName=(String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getExecEmpName");
		//任务创建人
		String createEmpId =(String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getCreateEmpId");
		//任务截至时间
		Date lastEndTime =  (Date) adminOptionInfo(joinPoint.getArgs(),methodName).get("getLastEndTime");
		//
		String   cycleTime= (String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getCycleTime");
		if(cycleTime.equals("NONE")){
		String content1 ="你有一个新的任务";
		bm.setId(Common.generateUUID());
		bm.setContent(content1);
		bm.setType("NEW");
		bm.setReadState("0");
		bm.setTaskId(taskId);
		bm.setAccpEmpId(accpEmpId);
		bm.setExpireTime(expireTime);
		bm.setCreateTime(date);
		bm.setDeleteState("0");
		bm.setCreateEmpId(createEmpId);
		bMessageService.insert(bm);
		}
	
		if((int)((lastEndTime.getTime()-date.getTime())/(1000*60*60*24))<1){
			String content2 ="你有一个任务即将逾期";
			bm1.setId(Common.generateUUID());
			bm1.setContent(content2);
			bm1.setType("DEADLINE");
			bm1.setReadState("0");
			bm1.setTaskId(taskId);
			bm1.setAccpEmpId(accpEmpId);
			bm1.setExpireTime(expireTime);
			bm1.setCreateTime(date);
			bm1.setDeleteState("0");
			bm1.setCreateEmpId(createEmpId);
			bMessageService.insert(bm1);
		 }
	  }

	/**
	 * 修改操作日志(后置通知)
	 * 
	 * @param joinPoint
	 * @param rtv
	 * @throws Throwable
	 */
	@AfterReturning(value="updateServiceCall()", argNames = "rtv", returning = "rtv")
	public void updateServiceCallCalls(JoinPoint joinPoint, Object rtv)
			throws Throwable {
		Date date = new Date();
		//过期时间
		Date expireTime = new Date(date.getTime()+24*60*60*1000);
		BMessage bm = new BMessage();
		if (joinPoint.getArgs() == null) {// 没有参数
			return;
		}
		// 获取方法名
		String methodName = joinPoint.getSignature().getName();
		// 获取操作内容
		//任务id
		String id = (String) adminOptionInfo(joinPoint.getArgs(), methodName).get("getId");
		//状态
		String comState=(String) adminOptionInfo(joinPoint.getArgs(),methodName).get("getComState");
		//获取该任务所有内容
		BTask btask=bTaskService.findById(id);
		String content= null;
		if("1".equals(comState)){
	        content=btask.getExecEmpName()+":更新了你发的任务状态：完成";
		}else{
			content = btask.getExecEmpName()+":取消了你发的任务完成状态";
		}
		bm.setId(Common.generateUUID());
		bm.setContent(content);
		bm.setType("COMPLETE");
		bm.setReadState("0");
		bm.setAccpEmpId(btask.getCreateEmpId());
		bm.setExpireTime(expireTime);
		bm.setCreateTime(date);
		bm.setDeleteState("0");
		bm.setTaskId(id);
		bm.setCreateEmpId(btask.getExecEmpId());
		bMessageService.insert(bm);
	}
	
	/**
	 * 使用Java反射来获取被拦截方法(insert、update)的参数值,将参数值拼接为Map
	 */
	public Map<String,Object> adminOptionInfo(Object[] args,String mName)throws Exception{
		if (args == null) {
			return null;
		}
		String className = null;
		int index=0;
		Map<String, Object> map = new HashMap<String,Object>();
		for (Object info : args) {
			className = info.getClass().getName();
			className = className.substring(className.lastIndexOf(".") + 1);
			// 获取对象的所有方法
			Method[] methods = info.getClass().getDeclaredMethods();
			// 遍历方法，判断get方法
			for (Method method : methods) {
				String methodName = method.getName();
				// 判断是不是get方法
				if (methodName.indexOf("get") == -1) {// 不是get方法
					continue;// 不处理
				}
				Object rsValue = null;
				try {
					// 调用get方法，获取返回值
					rsValue = method.invoke(info);
					if (rsValue == null) {// 没有返回值
						continue;
					}
				} catch (Exception e) {
					continue;
				}
				// 将值加入内容中
				map.put(methodName , rsValue);
			}
			index++;
		}
		return map;
	}
	
	/**
	 * 使用Java反射来获取被拦截方法(insert、update)的参数值， 将参数值拼接为操作内容
	 */
	public String adminOptionContent(Object[] args, String mName)
			throws Exception {
		if (args == null) {
			return null;
		}
		StringBuffer rs = new StringBuffer();
		rs.append(mName);
		String className = null;
		int index = 1;
		// 遍历参数对象
		for (Object info : args) {
			// 获取对象类型
			className = info.getClass().getName();
			className = className.substring(className.lastIndexOf(".") + 1);
			rs.append("[参数" + index + "，类型：" + className + "，值：");
			// 获取对象的所有方法
			Method[] methods = info.getClass().getDeclaredMethods();
			// 遍历方法，判断get方法
			for (Method method : methods) {
				String methodName = method.getName();
				// 判断是不是get方法
				if (methodName.indexOf("get") == -1) {// 不是get方法
					continue;// 不处理
				}
				Object rsValue = null;
				try {
					// 调用get方法，获取返回值
					rsValue = method.invoke(info);
					if (rsValue == null) {// 没有返回值
						continue;
					}
				} catch (Exception e) {
					continue;
				}
				// 将值加入内容中
				rs.append("(" + methodName + " : " + rsValue + ")");
			}
			rs.append("]");
			index++;
		}
		return rs.toString();
	}
}
